﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using DiscoveryLogic.Analytics.BusinessLogic.Entities;
using DiscoveryLogic.Analytics.DataObjects;
using DiscoveryLogic.Analytics.DataObjects.Rules;
using DiscoveryLogic.Common.Utilities;
using DiscoveryLogic.Common.Utilities.OpenXml;

namespace DiscoveryLogic.Analytics.BusinessLogic.Rules
{
    public class ImportRuleWorker
    {
        private EntityImportRule _Rule;
        /// <summary></summary>
        public EntityImportRule Rule
        {
            get
            {
                return this._Rule;
            }
            set
            {
                this._Rule = value;
            }
        }

        private string _DataSetName;
        /// <summary></summary>
        public string DataSetName
        {
            get
            {
                return this._DataSetName;
            }
            set
            {
                this._DataSetName = value;
            }
        }

        public ImportRuleWorker(EntityImportRule rule, string excelFilePath)
        {
            this._Rule = rule;
            this._Rule.DataSourcePath = excelFilePath;
            this._DataSetName = Path.GetFileNameWithoutExtension(excelFilePath);
        }

        public ImportRuleWorker(
            EntityImportRule rule, string excelFilePath, string dataSetName)
            : this(rule, excelFilePath)
        {
            this._DataSetName = dataSetName;
        }

        public List<EntityBase> RetrieveEntities()
        {
            EntityBase entity = (EntityBase) Activator.CreateInstance(EntityTypeUtil.GetType(this._Rule.SrcEntityType));
            SetDataProvider provider=new SetDataProvider();
            provider.DataSourcePath = this._Rule.DataSourcePath;
            provider.FieldPaths = this._Rule.EntityFieldSrcFieldMappings;
            provider.KeyFieldName = entity.IDField;
            provider.LabelField = entity.NameField;
            provider.RecordListPath = this._Rule.RecordListPath;
            provider.SetName = this._DataSetName;
            provider.SourceType = this._Rule.SrcDataFormat;
            DataTable dt = provider.GetDataFromProvider();
            return EntityManager.ToEntityList(this._Rule.TgtEntityType, dt, this._Rule.EntityFieldSrcFieldMappings);
        }
    }
}
